package com.xydtech.ecard.user.controller;

import com.alibaba.fastjson.JSONObject;
import com.xydtech.common.annotation.PassToken;
import com.xydtech.common.annotation.RsaRequest;
import com.xydtech.common.config.XydtechBusiPlatConfig;
import com.xydtech.common.core.domain.entity.SysDictData;
import com.xydtech.common.core.domain.entity.SysUser;
import com.xydtech.common.enums.ResultStatus;
import com.xydtech.common.model.ResponseModel;
import com.xydtech.common.utils.StringUtils;
import com.xydtech.common.utils.file.FileUploadUtils;
import com.xydtech.common.utils.file.MimeTypeUtils;
import com.xydtech.ecard.config.domain.EcardPrdInfo;
import com.xydtech.ecard.config.service.IEcardPrdInfoService;
import com.xydtech.ecard.ecard.controller.EcardApiBaseController;
import com.xydtech.ecard.user.domain.EcardApiAdeptPrdtype;
import com.xydtech.ecard.user.domain.EcardApiEcardRegistInfo;
import com.xydtech.ecard.user.domain.EcardApiHotPrd;
import com.xydtech.ecard.user.domain.EcardApiUserInfo;
import com.xydtech.ecard.user.service.IEcardApiEcardRegistInfoService;
import com.xydtech.ecard.user.service.IEcardApiUserService;
import com.xydtech.system.domain.SysWechatApplet;
import com.xydtech.system.service.ISysDictDataService;
import com.xydtech.system.service.ISysUserService;
import com.xydtech.system.service.ISysWechatAppletService;
import io.swagger.annotations.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 电子名片用户注册Controller
 *
 * @author Daniel
 * @date 2021-08-30
 */
@Controller
@Api(tags = "电子名片-用户注册相关")
@RequestMapping("/ecardSaasApi/regist")
public class EcardApiEcardRegistInfoController extends EcardApiBaseController {
    Logger logger = LoggerFactory.getLogger(EcardApiEcardRegistInfoController.class);
    //文件分布式存储开关
    @Value("${busiplat.minioUpload}")
    private boolean minioUpload;
    @Autowired
    private IEcardApiEcardRegistInfoService registInfoService;
    @Autowired
    private ISysUserService userService;
    @Autowired
    private ISysDictDataService dictDataService;
    @Autowired
    private IEcardPrdInfoService prdInfoService;
    @Autowired
    private ISysWechatAppletService wechatAppletService;
    @Autowired
    private ISysWechatAppletService sysWeChatAppletService;
    @Autowired
    private IEcardApiUserService ecardApiUserService;

    /**
     * 电子名片-创建工作室-上传头像
     * @param file
     * @return
     */
    @PostMapping("/uploadAvatar")
    @ApiOperation(value = "电子名片-创建工作室-上传头像", notes = "电子名片-创建工作室-上传头像")
    @ApiImplicitParams({@ApiImplicitParam(name = "avatarFile", value = "上传头像文件", dataType = "MultipartFile", dataTypeClass = MultipartFile.class, paramType = "query", required = true)})
    @ApiResponses({@ApiResponse(code = 0, message = "OK", response = ResponseModel.class)})
    @ResponseBody
    public ResponseModel uploadAvatar(@RequestParam("avatarFile") MultipartFile file) {
        try {
            String salt = getSalt();//盐值
            ////获取当前小程序对应的法人机构
            String currentUserId = getCurrentUserId();
            EcardApiUserInfo userInfo = ecardApiUserService.getUserInfo(currentUserId, salt);
            //当前小程序id
            SysWechatApplet wechatApplet = getAppIdByDeptId(userInfo.getDeptId());
            ////当前小程序对应的法人机构ID
            Long parentDeptId = wechatApplet.getDeptId();
            if (!file.isEmpty()) {
                //20230711 update 加入图片文件类型后缀判断
                String avatarFilePath = FileUploadUtils.uploadFileType(
                        XydtechBusiPlatConfig.getAvatarPath(parentDeptId), file, minioUpload, MimeTypeUtils.IMAGE_EXTENSION);
                registInfoService.updateAvatar(currentUserId, avatarFilePath);
                return ResponseModel.ok(avatarFilePath);
            } else {
                return ResponseModel.error("头像文件不能为空！");
            }
        } catch (Exception e) {
            logger.error("上传头像失败！", e);
            return ResponseModel.error(e.getMessage());
        }
    }

    /**
     * 电子名片-创建工作室-上传微信二维码
     * @param file
     * @return
     */
    @PostMapping("/uploadWechatQrcode")
    @ApiOperation(value = "电子名片-创建工作室-上传微信二维码", notes = "电子名片-创建工作室-上传微信二维码")
    @ApiImplicitParams({@ApiImplicitParam(name = "wechatQrcodeFile", value = "微信二维码", dataType = "MultipartFile", dataTypeClass = MultipartFile.class, paramType = "query", required = true)})
    @ApiResponses({@ApiResponse(code = 0, message = "OK", response = ResponseModel.class)})
    @ResponseBody
    public ResponseModel uploadWechatQrcode(@RequestParam("wechatQrcodeFile") MultipartFile file) {
        try {
            String salt = getSalt();//盐值
            String currentUserId = getCurrentUserId();
            if (!file.isEmpty()) {
                //获取当前小程序对应的法人机构
                EcardApiUserInfo userInfo = ecardApiUserService.getUserInfo(currentUserId, salt);
                //当前小程序id
                SysWechatApplet wechatApplet = getAppIdByDeptId(userInfo.getDeptId());
                //当前小程序对应的法人机构ID
                Long parentDeptId = wechatApplet.getDeptId();

                //20230711 update 加入图片文件类型后缀判断
                String wechatQrcodeFilePath = FileUploadUtils.uploadFileType(
                        XydtechBusiPlatConfig.getEcardFilePath() + "/" + parentDeptId + "/wechatQrcode", file, minioUpload,MimeTypeUtils.IMAGE_EXTENSION);
                registInfoService.updateWechatQrcode(currentUserId, wechatQrcodeFilePath);
                return ResponseModel.ok(wechatQrcodeFilePath);
            } else {
                return ResponseModel.error("微信二维码不能为空！");
            }
        } catch (Exception e) {
            logger.error("上传微信二维码失败！", e);
            return ResponseModel.error(e.getMessage());
        }
    }

    /**
     * 电子名片-创建工作室-获取头像和微信二维码路径
     * @return
     */
    @GetMapping("/getAvatarAndWechatQrcode")
    @ApiOperation(value = "电子名片-创建工作室-获取头像和微信二维码路径", notes = "电子名片-创建工作室-获取头像和微信二维码路径")
    @ApiResponses({@ApiResponse(code = 0, message = "OK", response = ResponseModel.class)})
    @ResponseBody
    public ResponseModel getAvatarAndWechatQrcode() {

        String currentUserId = getCurrentUserId();
        Map<String, Object> avatarAndWechatQrcodeMap = registInfoService.getAvatarAndWechatQrcode(currentUserId);
        return ResponseModel.ok(avatarAndWechatQrcodeMap);
    }

    /**
     * 电子名片-注册信息-完善用户信息
     * @return
     */
    @PostMapping("/completeUserInfo")
    @ApiOperation(value = "电子名片-电子名片-完善用户信息", notes = "电子名片-电子名片-完善用户信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "nickName", value = "用户昵称", dataType = "String", dataTypeClass = String.class, paramType = "body", required = true),
            @ApiImplicitParam(name = "avatarUrl", value = "头像路径", dataType = "String", dataTypeClass = String.class, paramType = "body", required = true)
    })
    @ApiResponses({@ApiResponse(code = 0, message = "OK", response = ResponseModel.class)})
    @ResponseBody
    public ResponseModel completeUserInfo(String nickName, String avatarUrl) {
        //获取当前用户ID
        String currentUserId = getCurrentUserId();

        int updateCount = registInfoService.completeUserInfo(currentUserId, nickName, avatarUrl);
        return updateCount > 0 ? ResponseModel.ok() : ResponseModel.error("完善用户信息操作失败！");
    }

    /**
     * 电子名片-创建工作室-信息完善
     * @param ecardRegistInfo
     * @return
     */
    @PostMapping(value = "/updateUserInfo", consumes = "application/json")
    @ApiOperation(value = "电子名片-创建工作室-信息完善", notes = "电子名片-创建工作室-信息完善")
    @ApiImplicitParams({@ApiImplicitParam(name = "ecardRegistInfo", value = "工作室信息", dataType = "EcardApiEcardRegistInfo", dataTypeClass = EcardApiEcardRegistInfo.class, paramType = "body", required = true)})
    @ApiResponses({@ApiResponse(code = 0, message = "OK", response = ResponseModel.class)})
    @ResponseBody
    @RsaRequest(result = true)
    public ResponseModel updateUserInfo(@RequestBody @Validated EcardApiEcardRegistInfo ecardRegistInfo) {
        String salt = getSalt();//盐值
        /**
         * 思路：
         * 1. 首先根据用户注册信息（userCode，wechatName，phoneno）查询下是否在sys_user表中存在，存在说明有效，不存在说明无效
         * 2. 然后再用userCode查询注册表（ecard_regist_info），判断userCode是否已经被占用了
         *  2.1 如果有占用，直接返回被xxxx用户名的xxxx手机号的用户占用了
         *  2.2 如果没有占用，更新用户信息到表中，同时更新roles为4-营销经理
         */
        String userCode = ecardRegistInfo.getUserCode();
        String wechatName = ecardRegistInfo.getWechatName();
        String phoneno = ecardRegistInfo.getPhoneno();

        //获取当前小程序对应的法人机构
        String currentUserId = getCurrentUserId();
        EcardApiUserInfo userInfo = ecardApiUserService.getUserInfo(currentUserId, salt);
        //当前小程序id
        SysWechatApplet wechatApplet = getAppIdByDeptId(userInfo.getDeptId());
        //当前小程序对应的法人机构ID
        Long parentDeptId = wechatApplet.getDeptId();
        JSONObject jsonObject=new JSONObject();
        /**
         * 查询sys_user表的user_code（userCode）、user_name（wechatName）、phonenumber（phoneno）、dept_id/parent_id(parentDeptId)是否存在对应的用户
         */
        SysUser user = userService.selectUserByWechatRegistInfo(userCode, wechatName, phoneno, salt);
        if (user == null) {
            return ResponseModel.error("抱歉，系统中暂未查询到对应信息的客户经理，无法创建工作室！");
        }

        EcardApiEcardRegistInfo registInfo = registInfoService.selectEcardApiEcardRegistInfoByUserCode(userCode, salt);
        if (registInfo != null) {
            return ResponseModel.error("该员工编号已被用户名为：" + registInfo.getWechatName() + "占用，请联系管理员进行解绑！");
        }

        //将当前用户ID塞入到对象中
        ecardRegistInfo.setRegistId(Long.parseLong(currentUserId));

        registInfoService.updateUserInfo(ecardRegistInfo, salt);
        jsonObject.put("code","0");
        return ResponseModel.okToJSON(jsonObject);
    }

    /**
     * 电子名片-创建工作室-获取产品大类
     * @return
     */
    @PassToken
    @GetMapping("/getPrdType")
    @ApiOperation(value = "电子名片-创建工作室-获取产品大类", notes = "电子名片-创建工作室-获取产品大类")
    @ApiResponses({@ApiResponse(code = 0, message = "OK", response = SysDictData.class)})
    @ResponseBody
    public ResponseModel getPrdType() {
        String salt = getSalt();//盐值
        //获取当前小程序对应的法人机构
        String currentUserId = getCurrentUserId();
        EcardApiUserInfo userInfo = ecardApiUserService.getUserInfo(currentUserId, salt);
        //当前小程序id
        SysWechatApplet wechatApplet = getAppIdByDeptId(userInfo.getDeptId());
        //当前小程序对应的法人机构ID
        Long parentDeptId = wechatApplet.getDeptId();

        List<SysDictData> sysDictDataList = registInfoService.getPrdType(parentDeptId);
        return ResponseModel.ok(sysDictDataList);
    }

    /**
     * 电子名片-创建工作室-获取产品详情
     * @return
     */
    @PassToken
    @GetMapping("/getPrdInfoList/{prdType}")
    @ApiOperation(value = "电子名片-创建工作室-获取产品详情", notes = "电子名片-创建工作室-获取产品详情")
    @ApiImplicitParams({@ApiImplicitParam(name = "prdType", value = "产品分类", dataType = "String", dataTypeClass = String.class, paramType = "query", required = true)})
    @ApiResponses({@ApiResponse(code = 0, message = "OK", response = EcardPrdInfo.class)})
    @ResponseBody
    public ResponseModel getPrdInfoList(@PathVariable("prdType") String prdType) {
        String salt = getSalt();//盐值
        String currentUserId = getCurrentUserId();
        EcardApiUserInfo userInfo = ecardApiUserService.getUserInfo(currentUserId, salt);
        //当前小程序id
        SysWechatApplet wechatApplet = getAppIdByDeptId(userInfo.getDeptId());
        String appId = wechatApplet.getAppid();
        if (StringUtils.isEmpty(appId)) {
            return ResponseModel.error(ResultStatus.PARAMETER_ERROR);
        }
        EcardPrdInfo ecardPrdInfo = new EcardPrdInfo();
        ecardPrdInfo.setPrdType(prdType);
        ecardPrdInfo.setDeptId(wechatApplet.getDeptId());
        ecardPrdInfo.setSts("1");
        ecardPrdInfo.setDictDeptId(wechatApplet.getDeptId());
        List<EcardPrdInfo> prdInfoList = prdInfoService.selectEcardPrdInfoList(ecardPrdInfo);
        return ResponseModel.ok(prdInfoList);
    }

    /**
     * 电子名片-创建工作室-保存擅长业务和优选产品
     * @return
     */
    @PostMapping("/saveAdeptPrdTypeAndHotPrd")
    @ApiOperation(value = "电子名片-创建工作室-保存擅长业务和优选产品", notes = "电子名片-创建工作室-保存擅长业务和优选产品")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "prdTypes", value = "产品分类", dataType = "String", dataTypeClass = String.class, paramType = "query", required = true),
            @ApiImplicitParam(name = "prdIds", value = "产品ID", dataType = "String", dataTypeClass = String.class, paramType = "query", required = true)})
    @ApiResponses({@ApiResponse(code = 0, message = "OK", response = ResponseModel.class)})
    @ResponseBody
    public ResponseModel saveAdeptPrdTypeAndHotPrd(
            @RequestParam(required = true) String prdTypes,
            @RequestParam(required = true) String prdIds) {

        //首先校验产品大类和产品ID是否正常
        if (prdTypes == null || StringUtils.isEmpty(prdTypes.replace(",", ""))) {
            return ResponseModel.error("请选择擅长领域！");
        }
        if (prdIds == null || StringUtils.isEmpty(prdIds.replace(",", ""))) {
            return ResponseModel.error("请选择推荐业务！");
        }
        String currentUserId = getCurrentUserId();
        String salt = getSalt();//盐值
        EcardApiUserInfo userInfo = ecardApiUserService.getUserInfo(currentUserId, salt);
        //当前小程序id
        SysWechatApplet wechatApplet = getAppIdByDeptId(userInfo.getDeptId());
        registInfoService.saveAdeptPrdTypeAndHotPrd(currentUserId, prdTypes, prdIds, wechatApplet.getDeptId());

        return ResponseModel.ok();
    }

    /**
     * 电子名片-创建工作室-获取客户经理擅长业务和优选产品
     * @return
     */
    @GetMapping("/getAdeptPrdTypeAndHotPrd")
    @ApiOperation(value = "电子名片-创建工作室-获取客户经理擅长业务和优选产品", notes = "电子名片-创建工作室-获取客户经理擅长业务和优选产品")
    @ApiResponses({@ApiResponse(code = 0, message = "OK", response = ResponseModel.class)})
    @ResponseBody
    public ResponseModel getAdeptPrdTypeAndHotPrd() {

        //获取当前登录人ID
        String currentUserId = getCurrentUserId();

        List<EcardApiAdeptPrdtype> ecardApiAdeptPrdtypeList = registInfoService.getAdeptPrdTypeList(currentUserId);
        List<EcardApiHotPrd> ecardApiHotPrdList = registInfoService.getHotPrdList(currentUserId);

        Map<String, Object> map = new HashMap<>();
        map.put("ecardApiAdeptPrdtypes", ecardApiAdeptPrdtypeList);
        map.put("ecardApiHotPrds", ecardApiHotPrdList);

        return ResponseModel.ok(map);
    }

    /**
     * 电子名片-创建工作室-获取业务预约模板ID
     * @return
     */
    @GetMapping("/getBusiReservationTemplateId")
    @ApiOperation(value = "电子名片-创建工作室-获取业务预约模板ID", notes = "电子名片-创建工作室-获取业务预约模板ID")
    @ApiResponses({@ApiResponse(code = 0, message = "OK", response = ResponseModel.class)})
    @ResponseBody
    public ResponseModel getBusiReservationTemplateId() {
        String salt = getSalt();//盐值
        String currentUserId = getCurrentUserId();
        EcardApiUserInfo userInfo = ecardApiUserService.getUserInfo(currentUserId, salt);
        //当前小程序id
        SysWechatApplet sysWechatApplet = getAppIdByDeptId(userInfo.getDeptId());
        //模板ID
        String templateId = sysWechatApplet.getTemplateId();
        return ResponseModel.ok(templateId);
    }

    /**
     * 电子名片-创建工作室-客户经理用户注销
     *
     * @return
     */
    @PostMapping("/logoffManagerUser")
    @ApiOperation(value = "电子名片-电子名片-客户经理用户解绑", notes = "电子名片-电子名片-客户经理用户解绑")
    @ApiImplicitParams({@ApiImplicitParam(name = "registId", value = "注册编号", dataType = "String", dataTypeClass = String.class, paramType = "query", required = true)})
    @ApiResponses({@ApiResponse(code = 0, message = "OK", response = ResponseModel.class)})
    @ResponseBody
    public ResponseModel logoffManagerUser(String registId) {
        if (StringUtils.isEmpty(registId)) {
            return ResponseModel.error(ResultStatus.PARAMETER_ERROR);
        }
        int i = registInfoService.logoffManagerUser(registId);
        return i > 0 ? ResponseModel.ok() : ResponseModel.error("解绑失败！");
    }
}
